package qq.android.wan.qq.recever;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.ListView;

import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.MessageBody;

import qq.android.wan.qq.chat.adapter.ListViewAdapter;
import qq.android.wan.qq.chat.activity.ChatActivity;
import qq.android.wan.qq.MyApplication;


/**
 * Created by Administrator on 2015/12/29.
 */
public class ChatNewMessageRecever extends BroadcastReceiver {
    private ListViewAdapter adapter;
    private ListView lv_chat_record;
    private ChatActivity activity;
    private EMConversation conversation;        //聊天对象
   public ChatNewMessageRecever(){}
    @Override
    public void onReceive(Context context, Intent intent) {
        EMMessage message = (EMMessage) intent.getParcelableExtra("date");
        MessageBody textMessageBody = (MessageBody) message.getBody();
        String username = null;
        // 群组消息
        if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
            username = message.getTo();
        } else {
            // 单聊消息
            username = message.getFrom();
            if (!username.equals(MyApplication.toChatUser)) {
                // 收到了新的消息，我们刷新title的未读数目,发送消息的人不是当前聊天的

            }
        }
        // 如果是当前会话的消息，刷新聊天页面
        if (username.equals(MyApplication.toChatUser)) {
            conversation.addMessage(message);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    adapter.notifyDataSetChanged();
                    lv_chat_record.setSelection(lv_chat_record.getCount() - 1);
                }
            });

        } else {
            // 如果消息不是和当前聊天ID的消息
            conversation.addMessage(message);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    adapter.notifyDataSetChanged();
                    lv_chat_record.setSelection(lv_chat_record.getCount() - 1);
                }
            });
        }
    }

    public ChatNewMessageRecever(ChatActivity activity, ListViewAdapter adapter,EMConversation conversation, ListView listView) {
        this.adapter = adapter;
        this.activity=activity;
        this.conversation=conversation;
        this.lv_chat_record = listView;
    }
}
